<template>
  <div class="ai-chat-container">
    <!-- 侧边栏 -->
    <div class="chat-sidebar" :class="{ collapsed: sidebarCollapsed }">
      <div class="sidebar-header">
        <el-button 
          type="primary" 
          @click="startNewChat"
          :icon="Plus"
          class="new-chat-btn"
          :loading="creatingChat"
          :disabled="creatingChat"
        >
          <span v-if="!sidebarCollapsed">新建对话</span>
        </el-button>
        <el-button 
          text
          @click="sidebarCollapsed = !sidebarCollapsed"
          :icon="sidebarCollapsed ? Menu : Fold"
          class="collapse-btn"
        />
      </div>
      
      <div class="chat-history" v-if="!sidebarCollapsed">
        <div 
          v-for="chat in chatHistory" 
          :key="chat.id"
          :class="['chat-item', { active: currentChatId === chat.id }]"
          @click="loadChat(chat.id)"
        >
          <el-icon class="chat-icon"><ChatDotRound /></el-icon>
          <span class="chat-title">{{ chat.title || '新对话' }}</span>
          <el-icon 
            class="delete-icon" 
            @click.stop="deleteChat(chat.id)"
          >
            <Delete />
          </el-icon>
        </div>
      </div>
    </div>

    <!-- 主聊天区域 -->
    <div class="chat-main">
      <!-- 头部工具栏 -->
      <div class="chat-header">
        <div class="header-left">
          <el-button text @click="showAgentCenter = true" :icon="Guide">
            智能体中心
          </el-button>
          <el-button text @click="showSettings = true" :icon="Setting">
            设置
          </el-button>
          <el-button text @click="clearCurrentChat" :icon="Delete">
            清空对话
          </el-button>
        </div>
        <div class="header-right">
          <el-tag 
            :type="!loading ? 'success' : 'warning'"
            size="small"
          >
            {{ loading ? '处理中' : '就绪' }}
          </el-tag>
        </div>
      </div>

      <!-- 消息列表 -->
      <div class="messages-container" ref="messagesContainer" @scroll="handleScroll">
        <div 
          v-for="(message, index) in messages" 
          :key="message.id || index"
          :class="['message-item', message.role, { 'message-new': message.isNew }]"
        >
          <div class="message-avatar">
            <el-avatar v-if="message.role === 'user'" :icon="User" />
            <el-avatar v-else :icon="Service" style="background: #409EFF;" />
          </div>
          <div class="message-content">
            <div class="message-header">
              <span class="message-role">
                {{ message.role === 'user' ? '您' : 'AI助手' }}
              </span>
              <span class="message-time">
                {{ formatTime(message.timestamp) }}
              </span>
            </div>
            <div class="message-text">
              <div 
                v-if="message.role === 'assistant1' && enableMarkdown"
                class="markdown-content"
                v-html="renderMarkdown(message.content)"
              ></div>
              <div v-else class="plain-content">
                {{ message.content }}
              </div>
            </div>
            <div class="message-actions" v-if="message.role === 'assistant'">
              <el-button 
                text 
                size="small"
                @click="copyMessage(message.content)"
                :icon="DocumentCopy"
              >
                复制
              </el-button>
              <el-button 
                text 
                size="small"
                @click="regenerateMessage(index)"
                :icon="Refresh"
                v-if="index === messages.length - 1"
              >
                重新生成
              </el-button>
            </div>
          </div>
        </div>
        
        <!-- 加载状态 -->
        <div v-if="loading" class="message-item assistant">
          <div class="message-avatar">
            <el-avatar :icon="Service" style="background: #409EFF;" />
          </div>
          <div class="message-content">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="chat-input-area">
        <div class="input-toolbar">
          <el-button 
            text 
            @click="toggleVoiceInput"
            :type="isVoiceInputActive ? 'primary' : ''"
            :icon="Microphone"
            :disabled="!enableVoiceInput"
            :class="{ 'voice-btn-active': isVoiceInputActive }"
          >
            语音输入
          </el-button>
          <el-button 
            text 
            @click="showQuickActions = true"
            :icon="Lightning"
          >
            快捷操作
          </el-button>
          <el-button 
            text 
            @click="formatInputMessage"
            :icon="Brush"
            :loading="prettierLoading"
          >
            格式化内容
          </el-button>
        </div>
        <div class="input-wrapper">
          <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="3"
            placeholder="输入您的问题，按 Ctrl+Enter 发送..."
            @keydown.ctrl.enter="sendMessage"
            @keydown.exact.enter.exact.prevent="handleEnterKey"
            ref="inputRef"
            :disabled="loading"
          />
          <el-button 
            type="primary" 
            @click="sendMessage"
            :disabled="!inputMessage.trim() || loading"
            :loading="loading"
            :icon="Promotion"
            class="send-btn"
          >
            发送
          </el-button>
        </div>
      </div>
    </div>

    <!-- 智能体中心 -->
    <el-drawer
      v-model="showAgentCenter"
      title="智能体配置中心"
      size="80%"
      direction="rtl"
      class="agent-center-drawer"
    >
      <AgentCenter />
    </el-drawer>

    <!-- 设置对话框 -->
    <el-drawer
      v-model="showSettings"
      title="AI设置"
      size="400px"
      direction="rtl"
    >
      <AISettings @close="showSettings = false" />
    </el-drawer>

    <!-- 快捷操作面板 -->
    <el-drawer
      v-model="showQuickActions"
      title="快捷操作"
      size="300px"
      direction="rtl"
    >
      <QuickActions @action="handleQuickAction" />
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick, computed, watch, watchEffect } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Plus, Menu, Fold, ChatDotRound, Delete, Setting, Refresh, 
  User, Service, DocumentCopy, Microphone, Lightning, Promotion, Guide, Brush
} from '@element-plus/icons-vue'
import { storeToRefs } from 'pinia'
import { createMultiSessionChat } from '@/uses/multiSessionChat'
import { marked } from 'marked'
import hljs from 'highlight.js/lib/core'
import javascript from 'highlight.js/lib/languages/javascript'
import typescript from 'highlight.js/lib/languages/typescript'
import json from 'highlight.js/lib/languages/json'
import xml from 'highlight.js/lib/languages/xml'
import python from 'highlight.js/lib/languages/python'
import shell from 'highlight.js/lib/languages/shell'
import bash from 'highlight.js/lib/languages/bash'
import yaml from 'highlight.js/lib/languages/yaml'
import sql from 'highlight.js/lib/languages/sql'
import css from 'highlight.js/lib/languages/css'
import scssLang from 'highlight.js/lib/languages/scss'
import markdownLang from 'highlight.js/lib/languages/markdown'
import 'highlight.js/styles/github.css'
import { createAiSession } from '@/api/aiSession'
import AISettings from './components/AISettings.vue'
import QuickActions from './components/QuickActions.vue'
import AgentCenter from './components/AgentCenter.vue'
import { useAgentStore } from '@/stores/agent'

const agentStore = useAgentStore()
agentStore.initialize()
const { activeAgent } = storeToRefs(agentStore)

const showAgentCenter = ref(false)

const getAgentGreeting = () => {
  const greeting = activeAgent.value?.prompt?.openingMessage?.trim()
  if (greeting && greeting.length > 0) {
    return greeting
  }
  return '你好！我是AI助手，有什么可以帮你的吗？'
}

const createWelcomeMessage = () => ({
  id: Date.now(),
  role: 'assistant',
  content: getAgentGreeting(),
  timestamp: Date.now()
})

// 多会话聊天管理
const {
  sendMessage: sendSSEMessage,
  setSessionMessages,
  getSessionMessages,
  getSessionLoading,
  setActiveChatId,
  getActiveMessages,
  getActiveLoading,
  deleteSession,
  activeChatId,
  sessions,
  ensureSessionRefs
} = createMultiSessionChat()

// UI状态 - 需要在 watch 之前声明
const currentChatId = ref(null)

// 当前激活会话的消息 ref
const messages = ref([])

// 当前激活会话的加载状态 ref
const loading = ref(false)

// 当前会话的 watch 停止函数
let currentSessionWatchStop = null
let messagesUpdateTimer = null

// 更新消息的防抖函数
const updateMessagesFromSession = (session) => {
  if (messagesUpdateTimer) {
    clearTimeout(messagesUpdateTimer)
  }
  messagesUpdateTimer = setTimeout(() => {
    if (session && session.messages) {
      messages.value = [...session.messages.value]
    }
    messagesUpdateTimer = null
  }, 50)
}

// 监听当前会话ID变化，同步消息和加载状态
watch(() => currentChatId.value, (newChatId) => {
  // 停止之前的 watch
  if (currentSessionWatchStop) {
    currentSessionWatchStop()
    currentSessionWatchStop = null
  }
  
  // 清除更新定时器
  if (messagesUpdateTimer) {
    clearTimeout(messagesUpdateTimer)
    messagesUpdateTimer = null
  }
  
  if (newChatId) {
    const session = sessions.get(newChatId)
    if (session) {
      ensureSessionRefs(session)
      
      // 立即更新
      messages.value = [...session.messages.value]
      loading.value = session.loading.value
      
      // 监听 session.messages 的变化（深度监听，用于流式更新）
      const messagesWatchStop = watch(
        () => session.messages.value,
        () => {
          updateMessagesFromSession(session)
        },
        { deep: true, immediate: false, flush: 'post' }
      )
      
      // 监听 session.loading 的变化
      const loadingWatchStop = watch(
        () => session.loading.value,
        (newLoading) => {
          loading.value = newLoading
        },
        { immediate: false }
      )
      
      // 合并所有停止函数
      currentSessionWatchStop = () => {
        if (messagesWatchStop) messagesWatchStop()
        if (loadingWatchStop) loadingWatchStop()
      }
      
      // 设置激活会话
      setActiveChatId(newChatId)
      
      // 滚动到底部
      nextTick(() => {
        scrollToBottom(false)
      })
    } else {
      messages.value = []
      loading.value = false
    }
  } else {
    messages.value = []
    loading.value = false
  }
}, { immediate: true })

// UI状态
const sidebarCollapsed = ref(false)
const showSettings = ref(false)
const showQuickActions = ref(false)
const creatingChat = ref(false)
const inputMessage = ref('')
const inputRef = ref(null)
const messagesContainer = ref(null)

// 语音输入
const isVoiceInputActive = ref(false)
const enableVoiceInput = ref(true)
const enableMarkdown = ref(true)
const enableCodeHighlight = ref(true)
const prettierReady = ref(false)
const prettierLoadState = ref('idle')
const prettierLoading = ref(false)

const sessionMetadata = reactive({})

const SUPPORTED_LANGUAGES = [
  { name: 'javascript', module: javascript },
  { name: 'typescript', module: typescript },
  { name: 'json', module: json },
  { name: 'html', module: xml },
  { name: 'xml', module: xml },
  { name: 'vue', module: xml },
  { name: 'python', module: python },
  { name: 'shell', module: shell },
  { name: 'bash', module: bash },
  { name: 'yaml', module: yaml },
  { name: 'yml', module: yaml },
  { name: 'sql', module: sql },
  { name: 'css', module: css },
  { name: 'scss', module: scssLang },
  { name: 'markdown', module: markdownLang },
  { name: 'md', module: markdownLang }
]

let highlightInitialized = false

const ensureHighlightRegistered = () => {
  if (highlightInitialized) return
  SUPPORTED_LANGUAGES.forEach(({ name, module }) => {
    if (!hljs.getLanguage(name)) {
      hljs.registerLanguage(name, module)
    }
  })
  highlightInitialized = true
}

const generateSessionKey = () => {
  if (typeof window !== 'undefined' && window.crypto?.randomUUID) {
    return window.crypto.randomUUID().replace(/-/g, '')
  }
  return `sess_${Date.now().toString(36)}_${Math.floor(Math.random() * 1e6)}`
}

const escapeHtml = (input = '') =>
  input
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;')

// 已移除 looksLikeCode 和 normalizeCodeSpacing 函数
// Markdown 将直接渲染，代码块等完整后才显示

let prettierLoadPromise = null
let prettierInstance = null
const prettierPlugins = []

const ensurePrettier = () => {
  if (prettierReady.value && prettierInstance && prettierPlugins.length) {
    return Promise.resolve(prettierInstance)
  }
  if (prettierLoadState.value === 'loading' && prettierLoadPromise) {
    return prettierLoadPromise
  }
  prettierLoadState.value = 'loading'
  prettierLoadPromise = Promise.all([
    import('prettier/standalone'),
    import('prettier/plugins/babel'),
    import('prettier/plugins/html'),
    import('prettier/plugins/postcss'),
    import('prettier/plugins/markdown'),
    import('prettier/plugins/typescript')
  ])
    .then(([prettier, babel, html, postcss, markdown, typescript]) => {
      prettierInstance = prettier?.default || prettier
      prettierPlugins.splice(
        0,
        prettierPlugins.length,
        babel?.default || babel,
        html?.default || html,
        postcss?.default || postcss,
        markdown?.default || markdown,
        typescript?.default || typescript
      )
      if (!prettierInstance || prettierPlugins.length === 0) {
        throw new Error('Prettier 模块加载失败')
      }
      prettierReady.value = true
      prettierLoadState.value = 'loaded'
      return prettierInstance
    })
    .catch((error) => {
      prettierLoadState.value = 'error'
      console.error('Prettier 加载失败:', error)
      throw error
    })
  return prettierLoadPromise
}

const applyAgentRuntimeConfig = (agent) => {
  if (!agent) return
  const toggles = agent.featureToggles || {}
  if (Object.prototype.hasOwnProperty.call(toggles, 'enableVoiceInput')) {
    enableVoiceInput.value = !!toggles.enableVoiceInput
  }
  if (Object.prototype.hasOwnProperty.call(toggles, 'enableMarkdown')) {
    enableMarkdown.value = !!toggles.enableMarkdown
  }
  if (Object.prototype.hasOwnProperty.call(toggles, 'enableCodeHighlight')) {
    enableCodeHighlight.value = !!toggles.enableCodeHighlight
  }
  if (enableCodeHighlight.value) {
    ensureHighlightRegistered()
  }
}

watch(
  activeAgent,
  (agent) => {
    applyAgentRuntimeConfig(agent)
  },
  { immediate: true, deep: true }
)

watch(
  enableCodeHighlight,
  (enabled) => {
    if (enabled) {
      ensureHighlightRegistered()
      if (messages.value?.length) {
        messages.value = [...messages.value]
      }
    }
  }
)

// 聊天历史
const chatHistory = ref([])

// 初始化聊天历史
const loadChatHistory = () => {
  try {
    const saved = localStorage.getItem('ai_chat_history')
    if (saved) {
      const parsed = JSON.parse(saved)
      if (Array.isArray(parsed)) {
        chatHistory.value = parsed.map((chat) => ({
          ...chat,
          sessionKey: chat.sessionKey || null,
          backendSessionId: chat.backendSessionId ?? null,
          agentId: chat.agentId ?? null
        }))
        chatHistory.value.forEach((chat) => {
          if (chat && chat.id) {
            sessionMetadata[chat.id] = {
              sessionKey: chat.sessionKey || null,
              backendSessionId: chat.backendSessionId ?? null
            }
          }
        })
      } else {
        chatHistory.value = []
      }
    }
  } catch (error) {
    console.error('加载聊天历史失败:', error)
  }
}

// 保存聊天历史
const saveChatHistory = () => {
  try {
    localStorage.setItem('ai_chat_history', JSON.stringify(chatHistory.value))
  } catch (error) {
    console.error('保存聊天历史失败:', error)
  }
}

// 新建对话
let pendingChatPromise = null

const startNewChat = (options = {}) => {
  const { title: providedTitle, skipSaveCurrent = false } = options
  if (creatingChat.value && pendingChatPromise) {
    return pendingChatPromise
  }
  if (currentChatId.value && !skipSaveCurrent) {
    saveCurrentChat(true)
  }

  creatingChat.value = true

  const promise = (async () => {
    const newChatId = Date.now()
    const baseTitle = (providedTitle && providedTitle.trim()) || '新对话'
    const initialMessage = createWelcomeMessage()

    let resolvedTitle = baseTitle
    let sessionKey = generateSessionKey()
    let backendSessionId = null

    try {
      const response = await createAiSession({
        title: baseTitle,
        sessionKey
      })
      if (response?.code === 200) {
        const data = response.data || {}
        resolvedTitle = data.title || resolvedTitle
        sessionKey = data.sessionKey || sessionKey
        backendSessionId = data.id ?? data.sessionId ?? null
      } else {
        throw new Error(response?.message || '会话创建失败')
      }
    } catch (error) {
      console.error('创建AI会话失败:', error)
      ElMessage.warning(error.message || '会话创建接口失败，已使用本地会话')
    }

    currentChatId.value = newChatId
    sessionMetadata[newChatId] = {
      sessionKey,
      backendSessionId
    }

    // 设置新会话的消息
    setSessionMessages(newChatId, [initialMessage])

    // 设置激活会话
    setActiveChatId(newChatId)

    // 添加到聊天历史
    const newChat = {
      id: newChatId,
      title: resolvedTitle,
      sessionKey,
      backendSessionId,
      messages: [initialMessage],
      createdAt: Date.now(),
      agentId: activeAgent.value?.id ?? null
    }
    chatHistory.value.unshift(newChat)
    saveChatHistory()

    // 滚动到底部
    nextTick(() => {
      scrollToBottom(false)
    })
  })().finally(() => {
    creatingChat.value = false
    pendingChatPromise = null
  })

  pendingChatPromise = promise
  return promise
}

// 加载对话
const loadChat = (chatId) => {
  // 如果切换的是同一个对话，不处理
  if (currentChatId.value === chatId) {
    return
  }
  
  // 先立即保存当前对话
  if (currentChatId.value) {
    saveCurrentChat(true) // 立即保存
  }
  
  // 加载新对话
  const chat = chatHistory.value.find(c => c.id === chatId)
  if (chat) {
    currentChatId.value = chatId
    if (chat.sessionKey || chat.backendSessionId) {
      sessionMetadata[chatId] = {
        sessionKey: chat.sessionKey || sessionMetadata[chatId]?.sessionKey || null,
        backendSessionId: chat.backendSessionId ?? sessionMetadata[chatId]?.backendSessionId ?? null
      }
    }
    
    // 确保消息列表被正确替换（深拷贝避免引用问题）
    let chatMessages = chat.messages && chat.messages.length > 0 
      ? JSON.parse(JSON.stringify(chat.messages))
      : [createWelcomeMessage()]
    
    // 确保每条消息都有 id
    chatMessages = chatMessages.map((msg, index) => {
      if (!msg.id) {
        msg.id = msg.timestamp || Date.now() + index
      }
      return msg
    })
    
    // 设置会话消息（如果会话正在执行，会继续在后台执行）
    setSessionMessages(chatId, chatMessages)
    
    // 设置激活会话（切换显示）
    setActiveChatId(chatId)
    
    // 滚动到底部
    nextTick(() => {
      scrollToBottom(false) // 切换对话时立即滚动，不使用平滑滚动
    })
  }
}

// 删除对话
const deleteChat = async (chatId) => {
  // 删除会话（会关闭连接）
  deleteSession(chatId)
  
  chatHistory.value = chatHistory.value.filter(c => c.id !== chatId)
  saveChatHistory()
  if (sessionMetadata[chatId]) {
    delete sessionMetadata[chatId]
  }
  if (currentChatId.value === chatId) {
    try {
      await startNewChat({ skipSaveCurrent: true })
    } catch (error) {
      console.error('删除后新建对话失败:', error)
    }
  }
}

// 清空当前对话
const clearCurrentChat = () => {
  if (!currentChatId.value) return
  
  const initialMessage = createWelcomeMessage()
  
  // 设置会话消息
  setSessionMessages(currentChatId.value, [initialMessage])
  
  // 清空后保存
  saveCurrentChat()
  
  // 滚动到底部
  nextTick(() => {
    scrollToBottom(false)
  })
}

// 保存防抖定时器
let saveTimer = null

// 保存当前对话到历史记录
const saveCurrentChat = (immediate = false) => {
  if (!currentChatId.value) return
  
  // 如果需要立即保存，清除防抖定时器并立即执行
  if (immediate) {
    if (saveTimer) {
      clearTimeout(saveTimer)
      saveTimer = null
    }
    _doSaveCurrentChat()
    return
  }
  
  // 防抖：延迟保存，避免频繁保存
  if (saveTimer) {
    clearTimeout(saveTimer)
  }
  
  saveTimer = setTimeout(() => {
    _doSaveCurrentChat()
    saveTimer = null
  }, 500) // 500ms 防抖延迟
}

// 执行保存操作
const _doSaveCurrentChat = () => {
  if (!currentChatId.value) return
  
  // 从会话中获取最新消息
  const sessionMessages = getSessionMessages(currentChatId.value)
  
  let chat = chatHistory.value.find(c => c.id === currentChatId.value)
  
  if (!chat) {
    // 如果不存在，创建新记录
    const firstUserMessage = sessionMessages.find(m => m.role === 'user')
    const meta = sessionMetadata[currentChatId.value] || {}
    chat = {
      id: currentChatId.value,
      title: firstUserMessage ? firstUserMessage.content.substring(0, 30) : '新对话',
      sessionKey: meta.sessionKey || null,
      backendSessionId: meta.backendSessionId ?? null,
      messages: [],
      createdAt: Date.now()
    }
    chatHistory.value.unshift(chat)
  }
  
  // 更新消息列表和标题（深拷贝避免引用问题）
  const meta = sessionMetadata[currentChatId.value] || {}
  if (meta.sessionKey && !chat.sessionKey) {
    chat.sessionKey = meta.sessionKey
  }
  if (meta.backendSessionId != null && chat.backendSessionId == null) {
    chat.backendSessionId = meta.backendSessionId
  }
  if (chat.agentId == null && activeAgent.value?.id) {
    chat.agentId = activeAgent.value.id
  }
  chat.messages = JSON.parse(JSON.stringify(sessionMessages))
  if (chat.title === '新对话' || !chat.title) {
    const firstUserMessage = sessionMessages.find(m => m.role === 'user')
    if (firstUserMessage) {
      chat.title = firstUserMessage.content.substring(0, 30)
    }
  }
  chat.updatedAt = Date.now()
  
  saveChatHistory()
}

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || loading.value) {
    return
  }

  const content = inputMessage.value.trim()
  inputMessage.value = ''
  
  // 如果还没有创建对话，先创建
  if (!currentChatId.value) {
    await startNewChat({
      skipSaveCurrent: true,
      title: content.substring(0, 30)
    })
  }

  if (!currentChatId.value) {
    ElMessage.error('创建会话失败，请重试')
    return
  }
  
  // 发送到SSE接口（会自动更新对应会话的消息）
  sendSSEMessage(content, currentChatId.value)
  
  // 滚动到底部
  nextTick(() => {
    scrollToBottom(true)
  })
}

// 处理Enter键
const handleEnterKey = () => {
  if (inputMessage.value.trim()) {
    sendMessage()
  }
}

// 复制消息
const copyMessage = (content) => {
  navigator.clipboard.writeText(content).then(() => {
    ElMessage.success('已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

// 重新生成消息
const regenerateMessage = (index) => {
  if (index < 1 || messages.value[index - 1].role !== 'user') {
    return
  }
  
  // 删除当前回复，重新发送
  const sessionMessages = getSessionMessages(currentChatId.value)
  sessionMessages.splice(index)
  setSessionMessages(currentChatId.value, sessionMessages)
  const userMessage = sessionMessages[index - 1].content
  sendSSEMessage(userMessage, currentChatId.value)
}

// 滚动状态管理
const isUserScrolling = ref(false)
const scrollTimeout = ref(null)
const lastScrollTop = ref(0)

// 检测用户是否在手动滚动
const handleScroll = () => {
  if (!messagesContainer.value) return
  
  const currentScrollTop = messagesContainer.value.scrollTop
  const maxScroll = messagesContainer.value.scrollHeight - messagesContainer.value.clientHeight
  
  // 如果用户向上滚动，标记为用户手动滚动
  if (currentScrollTop < lastScrollTop.value) {
    isUserScrolling.value = true
    if (scrollTimeout.value) {
      clearTimeout(scrollTimeout.value)
    }
    // 3秒后重置，允许自动滚动
    scrollTimeout.value = setTimeout(() => {
      isUserScrolling.value = false
    }, 3000)
  } else if (currentScrollTop >= maxScroll - 10) {
    // 如果滚动到底部附近，取消用户滚动标记
    isUserScrolling.value = false
  }
  
  lastScrollTop.value = currentScrollTop
}

// 平滑滚动到底部
const scrollToBottom = (smooth = true) => {
  if (!messagesContainer.value) return
  
  nextTick(() => {
    if (messagesContainer.value) {
      const container = messagesContainer.value
      const targetScroll = container.scrollHeight - container.clientHeight
      
      if (smooth) {
        // 使用平滑滚动
        container.scrollTo({
          top: targetScroll,
          behavior: 'smooth'
        })
      } else {
        // 立即滚动（用于初始加载）
        container.scrollTop = targetScroll
      }
    }
  })
}

// 智能滚动（流式更新时使用）
const scrollToBottomSmart = () => {
  if (!messagesContainer.value || isUserScrolling.value) {
    return // 如果用户正在手动滚动，不自动滚动
  }
  
  requestAnimationFrame(() => {
    if (!messagesContainer.value) return
    
    const container = messagesContainer.value
    const maxScroll = container.scrollHeight - container.clientHeight
    const currentScroll = container.scrollTop
    const distanceToBottom = maxScroll - currentScroll
    
    // 如果距离底部超过50px，使用平滑滚动
    // 如果距离底部小于50px，直接滚动（避免抖动）
    if (distanceToBottom > 50) {
      container.scrollTo({
        top: maxScroll,
        behavior: 'smooth'
      })
    } else {
      container.scrollTop = maxScroll
    }
  })
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

// 配置 marked 选项
marked.setOptions({
  breaks: true, // 支持 GitHub 风格的换行
  gfm: true, // 启用 GitHub 风格的 Markdown
  headerIds: false, // 禁用标题 ID
  mangle: false, // 不混淆邮箱地址
  sanitize: false, // 不禁用 HTML（因为我们使用 v-html）
  smartLists: true, // 智能列表
  smartypants: true, // 智能标点符号
  langPrefix: 'hljs language-',
  highlight(code, lang) {
    if (!enableCodeHighlight.value) {
      return code
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
    }
    ensureHighlightRegistered()
    if (lang && hljs.getLanguage(lang)) {
      return hljs.highlight(code, { language: lang, ignoreIllegals: true }).value
    }
    return hljs.highlightAuto(code).value
  }
})

// 渲染Markdown - 等代码块完整后才渲染
const renderMarkdown = (content) => {
  if (!content) return ''
  try {
    // 检查是否有未完成的代码块
    const codeBlockPattern = /```/g
    const matches = content.match(codeBlockPattern)
    const codeBlockCount = matches ? matches.length : 0
    
    // 如果代码块标记数量是奇数，说明有未闭合的代码块
    if (codeBlockCount % 2 !== 0) {
      // 找到最后一个 ``` 的位置
      const lastCodeBlockIndex = content.lastIndexOf('```')
      
      // 将内容分为两部分：完整部分 + 未完成部分
      const completePart = content.substring(0, lastCodeBlockIndex)
      const incompletePart = content.substring(lastCodeBlockIndex)
      
      // 只渲染完整部分，未完成部分显示为纯文本
      const completeHtml = completePart ? marked.parse(completePart) : ''
      const incompleteText = escapeHtml(incompletePart)
      
      return completeHtml + `<div class="incomplete-code">${incompleteText.replace(/\n/g, '<br>')}</div>`
    }
    
    // 所有代码块都完整，正常渲染
    const html = marked.parse(content)
    return html
  } catch (error) {
    console.error('Markdown 渲染错误:', error)
    // 如果解析失败，返回原始内容（转义 HTML）
    return content.replace(/</g, '&lt;').replace(/>/g, '&gt;')
  }
}

// 切换语音输入
const toggleVoiceInput = () => {
  if (!enableVoiceInput.value) return
  
  if (isVoiceInputActive.value) {
    // 停止语音输入
    isVoiceInputActive.value = false
  } else {
    // 启动语音输入
    startVoiceInput()
  }
}

// 启动语音输入
const startVoiceInput = () => {
  const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition
  
  if (!SpeechRecognition) {
    ElMessage.warning('当前浏览器不支持语音识别')
    return
  }
  
  const recognition = new SpeechRecognition()
  recognition.lang = 'zh-CN'
  recognition.continuous = false
  recognition.interimResults = true
  
  recognition.onstart = () => {
    isVoiceInputActive.value = true
    ElMessage.info('开始语音识别...')
  }
  
  recognition.onresult = (event) => {
    const result = event.results[event.results.length - 1]
    if (result.isFinal) {
      inputMessage.value = result[0].transcript
      isVoiceInputActive.value = false
      ElMessage.success('语音识别完成')
    }
  }
  
  recognition.onerror = () => {
    isVoiceInputActive.value = false
    ElMessage.error('语音识别失败')
  }
  
  recognition.onend = () => {
    isVoiceInputActive.value = false
  }
  
  recognition.start()
}

// 处理快捷操作
const handleQuickAction = (action) => {
  inputMessage.value = action.text
  showQuickActions.value = false
  nextTick(() => {
    inputRef.value?.focus()
  })
}

const formatInputMessage = async () => {
  const content = inputMessage.value
  if (!content || !content.trim()) {
    ElMessage.info('没有可格式化的内容')
    return
  }
  try {
    prettierLoading.value = true
    const prettier = await ensurePrettier()
    const formatted = prettier.format(content, {
      parser: 'markdown',
      plugins: prettierPlugins,
      tabWidth: 2,
      singleQuote: true,
      trailingComma: 'es5',
      semi: false,
      proseWrap: 'always'
    })
    inputMessage.value = formatted.trimEnd()
    ElMessage.success('内容已格式化')
  } catch (error) {
    console.error('格式化失败:', error)
    ElMessage.error('格式化失败，请检查代码是否正确')
  } finally {
    prettierLoading.value = false
  }
}

// 滚动防抖定时器
let scrollTimer = null
let rafId = null

// 监听消息数量变化，自动滚动和保存
watch(() => messages.value.length, () => {
  scrollToBottom(true)
  // 延迟保存，确保消息已经完全添加
  nextTick(() => {
    saveCurrentChat()
  })
}, { flush: 'post' })

// 保存防抖定时器
let saveWatchTimer = null

// 深度监听消息内容变化（用于流式更新AI回复内容）
// 使用 watchEffect 自动追踪依赖，更可靠
watchEffect(() => {
  // 访问 messages.value 以建立依赖追踪
  const msgs = messages.value
  const msgLength = msgs.length
  
  // 只在有消息时才处理
  if (msgLength > 0) {
    // 流式更新时使用智能滚动（只在用户未手动滚动时）
    if (scrollTimer) {
      clearTimeout(scrollTimer)
    }
    
    // 取消之前的 RAF
    if (rafId) {
      cancelAnimationFrame(rafId)
    }
    
    // 使用 RAF + 防抖组合，确保流畅且不抖动
    scrollTimer = setTimeout(() => {
      rafId = requestAnimationFrame(() => {
        scrollToBottomSmart()
        rafId = null
      })
      scrollTimer = null
    }, 100) // 100ms 防抖，减少滚动频率
    
    // 延迟保存，使用防抖避免频繁保存和递归更新
    if (saveWatchTimer) {
      clearTimeout(saveWatchTimer)
    }
    saveWatchTimer = setTimeout(() => {
      saveCurrentChat()
      saveWatchTimer = null
    }, 1000) // 1秒防抖，避免频繁保存
  }
}, { flush: 'post' })

// 监听当前会话ID变化已在上面定义，这里不需要重复

// 初始化
onMounted(() => {
  loadChatHistory()
  startNewChat({ skipSaveCurrent: true })
  loadAiSettings()
  if (enableCodeHighlight.value) {
    ensureHighlightRegistered()
  }
})

// 组件卸载时清理和保存
onUnmounted(() => {
  // 清理保存定时器
  if (saveTimer) {
    clearTimeout(saveTimer)
    // 立即保存当前对话
    if (currentChatId.value) {
      let chat = chatHistory.value.find(c => c.id === currentChatId.value)
      if (chat) {
        chat.messages = [...messages.value]
        saveChatHistory()
      }
    }
  }
  // 清理滚动定时器
  if (scrollTimer) {
    clearTimeout(scrollTimer)
  }
  if (rafId) {
    cancelAnimationFrame(rafId)
  }
  if (scrollTimeout.value) {
    clearTimeout(scrollTimeout.value)
  }
  // 清理保存监听定时器
  if (saveWatchTimer) {
    clearTimeout(saveWatchTimer)
  }
  // 清理会话 watch
  if (currentSessionWatchStop) {
    currentSessionWatchStop()
    currentSessionWatchStop = null
  }
  // 清理消息更新定时器
  if (messagesUpdateTimer) {
    clearTimeout(messagesUpdateTimer)
    messagesUpdateTimer = null
  }
})

// 加载AI设置
const loadAiSettings = () => {
  if (activeAgent.value) {
    applyAgentRuntimeConfig(activeAgent.value)
    return
  }
  try {
    const saved = localStorage.getItem('aiSettings')
    if (saved) {
      const settings = JSON.parse(saved)
      enableVoiceInput.value = settings.enableVoiceInput ?? true
      enableMarkdown.value = settings.enableMarkdown ?? true
      enableCodeHighlight.value = settings.enableCodeHighlight ?? true
      if (enableCodeHighlight.value) {
        ensureHighlightRegistered()
      }
    }
  } catch (error) {
    console.error('加载AI设置失败:', error)
  }
}
</script>

<style scoped lang="scss">
.ai-chat-container {
  display: flex;
  width: 100%;
  height: 100%;
  min-height: 0;
  background: #f5f5f5;
  overflow: hidden;
}

.chat-sidebar {
  width: 260px;
  background: #202123;
  color: #fff;
  display: flex;
  flex-direction: column;
  transition: width 0.3s;
  
  &.collapsed {
    width: 60px;
    
    .chat-history {
      display: none;
    }
  }
}

.sidebar-header {
  padding: 12px;
  display: flex;
  gap: 8px;
  border-bottom: 1px solid #3d3d3d;
}

.new-chat-btn {
  flex: 1;
}

.collapse-btn {
  color: #fff;
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.chat-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px;
  border-radius: 6px;
  cursor: pointer;
  margin-bottom: 4px;
  transition: background 0.2s;
  
  &:hover {
    background: #343541;
    
    .delete-icon {
      opacity: 1;
    }
  }
  
  &.active {
    background: #343541;
  }
}

.chat-icon {
  font-size: 16px;
  flex-shrink: 0;
}

.chat-title {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 14px;
}

.delete-icon {
  opacity: 0;
  transition: opacity 0.2s;
  cursor: pointer;
  
  &:hover {
    color: #f56c6c;
  }
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
  min-width: 0;
  min-height: 0;
  overflow: hidden;
}

.chat-header {
  padding: 12px 20px;
  border-bottom: 1px solid #e5e5e5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
}

.header-left,
.header-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 20px;
  background: #fff;
  min-height: 0;
  scroll-behavior: smooth;
  /* 优化滚动性能 */
  -webkit-overflow-scrolling: touch;
  will-change: scroll-position;
}

.message-item {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  
  /* 优化渲染性能 */
  will-change: transform, opacity;
  transform: translateZ(0);
  
  /* 新消息淡入动画 */
  &.message-new {
    animation: messageFadeIn 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  }
  
  &.user {
    flex-direction: row-reverse;
    
    .message-content {
      background: #409EFF;
      color: #fff;
      border-radius: 12px 12px 0 12px;
    }
  }
  
  &.assistant {
    .message-content {
      background: #f5f5f5;
      border-radius: 12px 12px 12px 0;
    }
  }
}

.message-avatar {
  flex-shrink: 0;
}

.message-content {
  flex: 1;
  max-width: 70%;
  padding: 12px 16px;
  word-wrap: break-word;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 12px;
  opacity: 0.7;
}

.message-role {
  font-weight: 500;
}

.message-time {
  font-size: 11px;
}

.message-text {
  line-height: 1.6;
  font-size: 14px;
}

.markdown-content {
  line-height: 1.6;
  word-wrap: break-word;
  
  :deep(h1) {
    font-size: 24px;
    margin: 16px 0 12px;
    font-weight: 600;
    border-bottom: 2px solid rgba(0, 0, 0, 0.1);
    padding-bottom: 8px;
  }
  
  :deep(h2) {
    font-size: 20px;
    margin: 14px 0 10px;
    font-weight: 600;
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    padding-bottom: 6px;
  }
  
  :deep(h3) {
    font-size: 18px;
    margin: 12px 0 8px;
    font-weight: 600;
  }
  
  :deep(h4), :deep(h5), :deep(h6) {
    margin: 10px 0 6px;
    font-weight: 600;
  }
  
  :deep(p) {
    margin: 8px 0;
    line-height: 1.6;
  }
  
  // 未完成的代码块样式
  :deep(.incomplete-code) {
    background: rgba(64, 158, 255, 0.05);
    border-left: 3px solid rgba(64, 158, 255, 0.3);
    padding: 12px;
    margin: 12px 0;
    border-radius: 4px;
    font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
    font-size: 0.9em;
    color: #666;
    white-space: pre-wrap;
    word-break: break-all;
    position: relative;
    
    &::after {
      content: '正在接收...';
      position: absolute;
      top: 8px;
      right: 12px;
      font-size: 12px;
      color: #409EFF;
      animation: dots 1.5s infinite;
    }
  }
  
  :deep(code) {
    background: rgba(0, 0, 0, 0.08);
    padding: 2px 6px;
    border-radius: 3px;
    font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
    font-size: 0.9em;
    color: #e83e8c;
  }
  
  :deep(pre) {
    padding: 12px;
    border-radius: 8px;
    overflow-x: auto;
    margin: 12px 0;
    border-left: 3px solid #409EFF;
    background: rgba(0, 0, 0, 0.05);
  }

  :deep(pre.hljs) {
    background: #f6f8fa;
  }

  :deep(pre code) {
    background: transparent;
    padding: 0;
    font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
    font-size: 0.9em;
  }
  
  :deep(blockquote) {
    border-left: 4px solid #409EFF;
    padding-left: 12px;
    margin: 12px 0;
    color: #666;
    background: rgba(64, 158, 255, 0.05);
    padding: 8px 12px;
    border-radius: 4px;
  }
  
  :deep(ul), :deep(ol) {
    padding-left: 24px;
    margin: 8px 0;
  }
  
  :deep(li) {
    margin: 4px 0;
    line-height: 1.6;
  }
  
  :deep(table) {
    border-collapse: collapse;
    width: 100%;
    margin: 12px 0;
    
    th, td {
      border: 1px solid rgba(0, 0, 0, 0.1);
      padding: 8px 12px;
      text-align: left;
    }
    
    th {
      background: rgba(0, 0, 0, 0.05);
      font-weight: 600;
    }
  }
  
  :deep(a) {
    color: #409EFF;
    text-decoration: none;
    
    &:hover {
      text-decoration: underline;
    }
  }
  
  :deep(hr) {
    border: none;
    border-top: 1px solid rgba(0, 0, 0, 0.1);
    margin: 16px 0;
  }
  
  :deep(img) {
    max-width: 100%;
    height: auto;
    border-radius: 4px;
    margin: 8px 0;
  }
  
  :deep(strong) {
    font-weight: 600;
  }
  
  :deep(em) {
    font-style: italic;
  }
}

.plain-content {
  white-space: pre-wrap;
}

.message-actions {
  margin-top: 8px;
  display: flex;
  gap: 8px;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 8px 0;
  
  span {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #409EFF;
    animation: typing 1.4s infinite;
    
    &:nth-child(2) {
      animation-delay: 0.2s;
    }
    
    &:nth-child(3) {
      animation-delay: 0.4s;
    }
  }
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.7;
  }
  30% {
    transform: translateY(-10px);
    opacity: 1;
  }
}

.chat-input-area {
  padding: 16px 20px;
  border-top: 1px solid #e5e5e5;
  background: #fff;
}

.input-toolbar {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
}

.input-wrapper {
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.send-btn {
  height: fit-content;
  align-self: flex-end;
}

/* 语音输入按钮动画 */
.voice-btn-active {
  animation: voice-pulse-btn 1.5s ease-in-out infinite;
  position: relative;
  overflow: visible;
}

.voice-btn-active::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  height: 100%;
  border-radius: 4px;
  background: rgba(64, 158, 255, 0.3);
  animation: voice-ripple 1.5s ease-in-out infinite;
  pointer-events: none;
  z-index: 0;
}

.voice-btn-active :deep(.el-icon) {
  position: relative;
  z-index: 1;
  animation: voice-icon-pulse 1.2s ease-in-out infinite;
}

@keyframes voice-pulse-btn {
  0%, 100% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.7);
  }
  50% {
    transform: scale(1.05);
    box-shadow: 0 0 0 8px rgba(64, 158, 255, 0);
  }
}

@keyframes voice-ripple {
  0% {
    transform: translate(-50%, -50%) scale(1);
    opacity: 0.8;
  }
  100% {
    transform: translate(-50%, -50%) scale(1.5);
    opacity: 0;
  }
}

@keyframes voice-icon-pulse {
  0%, 100% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.15);
    opacity: 0.9;
  }
}

@keyframes dots {
  0%, 20% {
    content: '正在接收.';
  }
  40% {
    content: '正在接收..';
  }
  60%, 100% {
    content: '正在接收...';
  }
}

/* 消息淡入动画 - 更流畅的缓动函数 */
@keyframes messageFadeIn {
  from {
    opacity: 0;
    transform: translateY(15px) scale(0.98);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

/* 流式更新时的平滑过渡 */
.message-item.assistant .message-content {
  transition: min-height 0.15s ease-out;
}

/* 流式更新文本时的平滑效果 */
.message-item.assistant .message-text {
  transition: opacity 0.1s ease-out;
}

/* 优化消息内容渲染 */
.message-text {
  line-height: 1.6;
  font-size: 14px;
  word-break: break-word;
  /* 优化文本渲染 */
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
}

:deep(.agent-center-drawer .el-drawer__body) {
  padding: 0;
  background: #f6f7fb;
}
</style>
